import store from "@/store/index.js"
export default class MeetingWebSocket {
	constructor() {
		this.socket = null
		this._business_id = null
		this.status = 0 //0:空闲，1:已接听，2:正在发送呼叫请求，3:正在被呼叫

		this._remote_info = {} //远程联系对象{sendUserId, sendDoctorName, sendOrgName, receiveUserId, receiveUserName, receiveOrgId, receiveOrgName, msg}

		this._subscribers = { //订阅事件
			'status': [], //状态变更事件订阅者
			'receive': [], //接受事件订阅者
		}
		this._calling_interval = null //呼叫定时器

		// 添加重连相关配置
		this.reconnectAttempts = 0
		this.maxReconnectAttempts = 5
		this.reconnectInterval = 5000 // 重连间隔5秒
		this.wsUrl = '' // 保存 WebSocket URL

		// 添加心跳监控相关配置
		this.lastPingTime = 0 // 最后一次发送ping的时间
		this.lastPongTime = 0 // 最后一次收到pong的时间
		this.connectionLatency = 0 // 连接延迟时间
		this.heartbeatTimeout = 10000 // 心跳超时时间（10秒）
	}

	init(url) {
		this.wsUrl = url // 保存 URL 用于重连
		this.connectWebSocket(url)
	}

	connectWebSocket(url) {
		if(!this.socket==null){
			this.close()
		}
		this.socket = uni.connectSocket({
			url,
			success: (response) => {
				console.log('链接成功', response)
				this.reconnectAttempts = 0 // 重置重连次数
			},
			fail: (error) => {
				console.log('连接失败', error)
				// this.reconnect()
			}
		})

		//监听收到消息
		this.socket.onMessage((e) => {
			let data = null
			if (typeof JSON.parse(e.data) === "object") {
				data = JSON.parse(e.data)
			} else {
				data = JSON.parse(JSON.parse(e.data))
			}
			// let data = JSON.parse(JSON.parse(e.data))
			let msg = data.msg
			console.log('接收到消息', data)

			if (data.type === 'calling') { //收到呼叫请求

				this._setStatus(3)

				this._emit('receive', data)

				// 更新联系对象信息
				this._remote_info = {
					userId: data.sendUserId,
					doctorName: data.sendUserName
				}
				this._business_id = data.businessId
				// 存储来电信息到vuex
				store.state.$userInfo = {
					type: data.type,
					orgName: data.sendOrgName,
					userName: data.sendUserName,
					businessId: data.businessId
				}

				const speech = new SpeechSynthesisUtterance('您有一个及时会诊，请接听')
				window.speechSynthesis.speak(speech)

			} else if (data.type === 'call_cancel') { //收到对方取消呼叫消息(此版本暂时不用)

				this._setStatus(0) //修改状态为:空闲

				this._emit('receive', data)

			} else if (data.type === 'answer') { //收到对方已接听消息

				this._local_info = {
					userId: data.sendUserId,
					doctorName: data.sendUserName
				}
				this._business_id = data.businessId

				this._setStatus(1) //修改状态为:已接听

				this._emit('receive', data)

			} else if (data.type === 'busy') { //对方忙碌

				this._setStatus(0) //修改状态为:空闲

				this._emit('receive', data)

			} else if (data.type === 'leave') { //对方挂断会议

				this._emit('receive', data)

			} else if (data.type === 'pong') { // 处理心跳响应
				const currentTime = new Date().getTime()
				this.lastPongTime = currentTime

				// 计算延迟时间（往返时间）
				if (data.msg && data.msg.timestamp) {
					this.connectionLatency = currentTime - data.msg.timestamp
					console.log('当前连接延迟：', this.connectionLatency + 'ms')
				}

				// 重置心跳状态
				this.lastPingTime = 0
			}
		})

		// 监听关闭事件
		this.socket.onClose((res) => {
			console.log('WebSocket监听关闭事件',res)
			if (res.code != 1000) {
				console.log('非正常退出',res)
				this.close()
				this.reconnect()
			}
		})

		// 监听错误事件
		this.socket.onError((res) => {
			console.log('WebSocket连接错误', res)
			this.close()
			// this.reconnect()
			uni.showToast({
				title: 'WebSocket连接错误，请检测网络并刷新尝试',
				duration: 2000,
				icon:'error'
			});
			
		})

		// 启动心跳检测
		this.startHeartbeat()
	}
	// 关闭连接
	close(){
		if(this.socket!=null){
			this.socket.close({
				success:(res)=>{
					console.log('成功关闭',res)
				},
				fail:(res)=>{
					console.log('关闭失败',res)
				}
			})
			this.stopHeartbeat()
			this.socket=null
		}
		
	}
	// 重连方法
	reconnect() {
		if (this.reconnectAttempts >= this.maxReconnectAttempts) {
			console.log('WebSocket重连次数超过最大限制')
			uni.showToast({
				title: 'WebSocket重连次数超过最大限制,请检测网络并刷新尝试',
				duration: 2000,
				icon:'error'
			});
			return
		}

		// 重置心跳相关状态
		this.lastPingTime = 0
		this.lastPongTime = 0
		this.connectionLatency = 0

		console.log(`尝试第 ${this.reconnectAttempts + 1} 次重连...`)
		setTimeout(() => {
			this.reconnectAttempts++
			this.connectWebSocket(this.wsUrl)
		}, this.reconnectInterval)
	}

	// 心跳检测
	startHeartbeat() {
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval)
		}

		this.heartbeatInterval = setInterval(() => {
			if (this.socket && this.socket.readyState === 1) {
				const currentTime = new Date().getTime()

				// 检查上一次心跳是否超时
				if (this.lastPingTime && !this.lastPongTime && (currentTime - this.lastPingTime > this
						.heartbeatTimeout)) {
					console.log('心跳检测超时，准备重连...')
					this.reconnect()
					return
				}

				this.lastPingTime = currentTime
				this.sendMsg({
					type: 'ping',
				})
			}
		}, 20000) // 每20秒发送一次心跳
	}
	// 停止心跳检测
	stopHeartbeat() {
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval)
			this.heartbeatInterval = null
		}
	}
	

	_setStatus(status, payLoad) {
		this.status = status
		this._emit('status', {
			status: this.status,
			data: payLoad ? {
				...payLoad
			} : null
		})

		if (status == 0) { //空闲状态，清除相关数据信息
			this._business_id = null
			this._remote_info = null
		}
	}

	_emit(event, data) {
		if (this._subscribers[event]) {
			for (let i = 0; i < this._subscribers[event].length; i++) {
				this._subscribers[event][i](data)
			}
		}
	}

	bind(event, subscriber) {
		this._subscribers[event].push(subscriber)
	}

	unbind(event, subscriber) {
		let index = this._subscribers[event].findIndex(item => {
			return item == subscriber
		})
		if (index > -1) {
			this._subscribers[event][index] == null
			this._subscribers[event].splice(index, 1)
		}

	}

	/**
	 * 呼叫对方进行会议
	 * @param {Object} option 消息对象
	 * @param {String} option.businessId 业务ID
	 * @param {String} option.receiveOrgId 接收机构名称
	 * @param {String} option.receiveOrgName 接收机构名称
	 */
	calling(option) {
		return new Promise((resolve, reject) => {

			let sendData = {
				type: 'calling',
				msg: {},
				receiveOrgName: option.receiveOrgName,
				receiveOrgId: option.receiveOrgId,
				businessId: option.businessId
			}
			this.sendMsg(sendData, {
				...option
			})

			this._setStatus(2, option) //修改状态为:正在发送呼叫请求

			//更新联系对象信息
			this._remote_info = {
				orgName: sendData.receiveOrgName,
				orgId: sendData.receiveOrgId
			}
			//更新业务ID
			this._business_id = sendData.businessId


			let times = 0;

			let interval = setInterval(() => {
				times++;

				if (this.status == '2' && times <= 20) {

					sendData.type = 'calling'
					this.sendMsg(sendData)

				} else {
					if (this.status == '1') { //已接听

						clearInterval(this._calling_interval)
						this._calling_interval = null

						resolve('success')

					} else if (times > 20) { //呼叫超时

						sendData.type = 'call_timeout'
						this.sendMsg(sendData)

						clearInterval(this._calling_interval) //清除定时器
						this._calling_interval = null

						this._setStatus(0) //修改状态为:空闲

						resolve('timeout')

					} else { //呼叫错误，已断线

						sendData.type = 'call_error'
						this.sendMsg(sendData)

						clearInterval(this._calling_interval) //清除定时器
						this._calling_interval = null

						this._setStatus(0) //修改状态为:空闲

						reject('error')

					}

				}
			}, 6000)

			if (this._calling_interval) { //存在定时器，则清除旧的定时器
				clearInterval(this._calling_interval)
				this._calling_interval = null
			}

			this._calling_interval = interval

		})
	}

	/**
	 * 发送取消呼叫消息
	 */
	cancelCall() {


		clearInterval(this._calling_interval) //清除定时器
		this._calling_interval = null
		let sendData = {
			msg: {},
			type: 'call_cancel',
			receiveOrgName: this._remote_info.orgName,
			receiveOrgId: this._remote_info.orgId,
			businessId: this._business_id
		}
		this._setStatus(0) //修改状态为:空闲
		this.sendMsg(sendData)
	}

	/**
	 * 离开会议
	 */
	leave() {
		let sendData = {
			type: 'leave',
			msg: {},
			receiveOrgName: this._remote_info.orgName ? this._remote_info.orgName : this._remote_info
				.doctorName,
			receiveOrgId: this._remote_info.orgId ? this._remote_info.orgId : this._remote_info.userId,
			businessId: this._business_id
		}
		this.sendMsg(sendData)
		this.stopHeartbeat() // 停止心跳检测
		this._setStatus(0) //修改状态为:空闲
	}

	/**
	 * 接听会诊呼叫
	 */
	answer() {
		let sendData = {
			msg: {},
			type: 'answer',
			receiveOrgName: this._remote_info.orgName,
			receiveUserId: this._remote_info.userId,
			businessId: this._business_id
		}
		this.sendMsg(sendData)

		this._setStatus(1) //修改状态为:已接听

		clearInterval(this._calling_interval) //清除定时器
		this._calling_interval = null
	}

	/**
	 * 发送消息
	 * @param {Object} option 消息对象
	 * @param {String} option.businessId 业务ID
	 * @param {String} option.receiveUserId 接收人ID
	 * @param {String} option.receiveUserName 接收人名称
	 * @param {String} option.receiveOrgId 接收人名称
	 * @param {String} option.receiveOrgName 接收机构名称
	 * @param {Object} option.msg 发送的消息信息
	 * @param {String} option.msg.type 发送的消息类型
	 */
	sendMsg(option) {
		option.sendUserId = uni.getStorageSync('doctorId')
		option.sendUserName = uni.getStorageSync('doctorName')
		option.sendOrgName = uni.getStorageSync('hospitalName')
		console.log('发送消息', option)
		this.socket.send({
			data: JSON.stringify(option)
		})
	}

}